package com.axend.aerosense.dev.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.ILoginStatusChanged;
import com.axend.aerosense.base.utils.ThreadPoolUtils;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.base.ITitle;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.connect.bean.BleScanResultBean;
import com.axend.aerosense.common.connect.impl.IScanResult;
import com.axend.aerosense.common.connect.impl.IScanStateCallback;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.common.util.ImageSaveUtil;
import com.axend.aerosense.dev.BR;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.activity.DevBaseWifiActivity;
import com.axend.aerosense.dev.activity.NewDevSetNetActivity;
import com.axend.aerosense.dev.adapter.DevChooseDeviceAdapter;
import com.axend.aerosense.dev.adapter.DevScanDeviceAdapter;
import com.axend.aerosense.base.database.device.DeviceInfoManager;
import com.axend.aerosense.dev.databinding.DevFragmentChooseDeviceBinding;
import com.axend.aerosense.base.bean.ChooseDeviceBean;
import com.axend.aerosense.dev.viewmodel.ChooseDeviceViewModel;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.UriUtils;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

public class DevChooseDeviceFragment
        extends MvvmBaseFragment<DevFragmentChooseDeviceBinding, ChooseDeviceViewModel>
        implements ILoginStatusChanged, ILoadDataResult<ChooseDeviceBean>, IScanStateCallback {

    public static final String RADAR_TYPE = "RADAR_TYPE";

    private DevChooseDeviceAdapter adapter;
    private DevScanDeviceAdapter scanDeviceAdapter;
    private RadarType type;
    private boolean isScanDevice = false;

    public static DevChooseDeviceFragment getInstance() {
        DevChooseDeviceFragment fragment = new DevChooseDeviceFragment();
        return fragment;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setLoadSir(viewDataBinding.devContentView);
        onRetryBtnClick();
        initView();
    }

    private void initView() {
        //扫描到的设备列表
        scanDeviceAdapter = new DevScanDeviceAdapter();
        viewDataBinding.devRvSearchDeviceList.setLayoutManager(new GridLayoutManager(getContext(), 2));
        viewDataBinding.devRvSearchDeviceList.setAdapter(scanDeviceAdapter);
        scanDeviceAdapter.setOnItemClickListener(deviceType -> {
            clickListItem(deviceType);
        });

        //手动添加设备列表
        adapter = new DevChooseDeviceAdapter();
        viewDataBinding.devDeviceList.setLayoutManager(new GridLayoutManager(getContext(), 2));
        viewDataBinding.devDeviceList.setAdapter(adapter);
        adapter.setOnItemClickListener(type -> {
            clickListItem(type);
        });

        viewDataBinding.devTvAutoSearch.setOnClickListener(v -> {
            if (!viewModel.isSearch.getValue()) {
                startFindDevice();
            }
        });

        viewModel.searchFlag.observe(getViewLifecycleOwner(), integer -> {
            viewDataBinding.devLtView.setVisibility(integer == 0 ? View.VISIBLE : View.GONE);
        });
        startFindDevice();
    }

    private void clickListItem(RadarType type) {
        //设备点击
        this.type = type;
        getWifiActivity().setDeviceType(type);
        toNextPager();
    }

    private DevBaseWifiActivity getWifiActivity() {
        FragmentActivity activity = getActivity();
        if (activity instanceof DevBaseWifiActivity) {
            return (DevBaseWifiActivity) activity;
        }
        return null;
    }

    private void toNextPager() {
        Fragment fragment;

        if (type == RadarType.ASSURE) {
            fragment = DevConnectWifiFragment.getInstance();
        } else {
            fragment = DevFamilyWifiFragment.getInstance();
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable(RADAR_TYPE, type);
        fragment.setArguments(bundle);
        FragmentUtil.add(
                getActivity(),
                ((NewDevSetNetActivity) getActivity()).getContentId(),
                fragment,
                this,
                true
        );
    }

    /**
     * 开始播放搜索动画
     */
    private void startSearchAnimation() {
        viewDataBinding.devLtView.playAnimation();
    }

    /**
     * 停止播放搜索动画
     */
    private void stopSearchAnimation() {
        viewDataBinding.devLtView.pauseAnimation();
    }

    /**
     * 开始查找设备
     */
    private void startFindDevice() {

        //startBleScanResultTimer();
        startSearchAnimation();
        viewModel.searchFlag.setValue(0);
        viewModel.isSearch.setValue(true);
        isScanDevice = false;
        getWifiActivity().getDeviceConnectManager().startBleScan();
    }

    /**
     * 停止查找设备
     */
    private void stopFindDevice() {
        //stopBleScanResultTimer();
        stopSearchAnimation();
        if (!isScanDevice) {
            viewModel.searchFlag.setValue(2);
        }
        viewModel.isSearch.setValue(false);
    }

    /**
     * 更新扫描到的设备列表
     *
     * @param scanResult
     */
    private void updateScanDeviceList(List<IScanResult> scanResult) {
        LogUtils.d(scanResult);
        if (null == scanResult || scanResult.isEmpty()) {
            return;
        }

        List<BleScanResultBean> scanResultBeanList = new ArrayList<>();
        for (IScanResult result : scanResult) {
            BleScanResultBean bean = (BleScanResultBean) result;
            if (null != bean.getRadarType()) {
                scanResultBeanList.add(bean);
            }
        }
        if (scanResultBeanList.size() > 0) {
            scanDeviceAdapter.upDateList(scanResultBeanList);
            viewModel.searchFlag.setValue(1);
        }
    }


    public static void saveImage(Context context, List<ChooseDeviceBean.DeviceInfo> data) {
        ConcurrentLinkedQueue<ChooseDeviceBean.DeviceInfo> imageLinkedQueue = new ConcurrentLinkedQueue<>();

        if (imageLinkedQueue != null)
            imageLinkedQueue.clear();
        for (ChooseDeviceBean.DeviceInfo entity : data) {
            imageLinkedQueue.offer(entity);
        }
        ThreadPoolUtils.getInstance().execute(() -> {
            while (!imageLinkedQueue.isEmpty()) {
                ChooseDeviceBean.DeviceInfo deviceInfo = imageLinkedQueue.peek();

                ChooseDeviceBean.DeviceInfo localDeviceInfo=DeviceInfoManager.getInstance(context).deviceInfoDao().queryDeviceType(deviceInfo.getRadarType());


                RadarType radarType = RadarType.getType(deviceInfo.getRadarType());
                Bitmap bitmap = ImageSaveUtil.getBitmap(deviceInfo.getRadarTypeUrl());
                Uri uri = ImageSaveUtil.saveLocal(context, localDeviceInfo!=null? Uri.parse(localDeviceInfo.getFileUri()) :null,bitmap,context.getString(radarType.getName()), Bitmap.CompressFormat.PNG, 100, true);

                if (uri != null) {
                    deviceInfo.setFileUri(uri.toString());
                    DeviceInfoManager.getInstance(context).deviceInfoDao().insert(deviceInfo);
                }
                imageLinkedQueue.poll();
            }

        });
    }

    @Override
    public void onResume() {
        super.onResume();
        ((ITitle) getActivity()).setTitle(getString(R.string.dev_choose_your_device));
    }

    @Override
    public int getLayoutId() {
        return R.layout.dev_fragment_choose_device;
    }

    @Override
    public int getBindingVariable() {
        return BR.viewModel;
    }

    @Override
    protected ChooseDeviceViewModel getViewModel() {
        BaseViewModelFactroy<ChooseDeviceBean> factroy = new BaseViewModelFactroy<>(this, this);
        return new ViewModelProvider(this, factroy).get(ChooseDeviceViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    public void loadDataSuccess(ChooseDeviceBean deviceBean) {
        if (deviceBean != null && deviceBean.getRadarTypeInfo() != null && !deviceBean.getRadarTypeInfo().isEmpty()) {
            List<ChooseDeviceBean.DeviceInfo> list = deviceBean.getRadarTypeInfo();
            if (list.size() > 3) Collections.swap(list, 1, 2);
            adapter.upDateList(list);
            saveImage(getActivity(), list);
            showContent();
        } else {
            showEmpty();
        }
    }

    @Override
    public void loadDataFail(String decs) {
        showFailure(decs);
    }

    @Override
    public void loginStatusChanged() {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //页面切出去时，停止扫描
            stopFindDevice();
            getWifiActivity().getDeviceConnectManager().stopBleScan();
        } else {
            startSearchAnimation();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        viewDataBinding.devLtView.cancelAnimation();
        getWifiActivity().getDeviceConnectManager().stopBleScan();
        stopFindDevice();
    }

    @Override
    public void scanResult(List<IScanResult> list) {
        if (null == list || list.isEmpty()) {
            return;
        }

        if (list.get(0) instanceof BleScanResultBean) {
            isScanDevice = true;
            updateScanDeviceList(list);
        }
    }

    @Override
    public void scanState(int state) {
        if (state == IScanStateCallback.SCAN_COMPLETE) {
            stopFindDevice();
        }
    }
}